function showCoupon() {
	mask.open(true);
	ajaxGet(website + "boCoupon/show", null, function(result) {
		var tabOrder = $("#currentTabOrder").val();
		$("#tabs-"+tabOrder).html(result);
		initCoupon();
		mask.close();
	}, "html");
}

function initCoupon() {
	$("#create-coupon").button().click(function() {
		addOrEditCouponDialog(ACTION_ADD);
	});
	
	$("#edit-coupon").button().click(function() {
		addOrEditCouponDialog(ACTION_EDIT);
	});

	$("#delete-coupon").button().click(function() {
		openDeleteDialog(COUPON,"checkKey");
	});
	
	$(".editCouponBtn").button().click(function() {
		addOrEditCouponDialog(ACTION_EDIT, $(this).attr("couponid"));
	});

	$(".delCouponBtn").button().click(function() {
		openDeleteDialog(COUPON,"checkKey",$(this).attr("couponid"));
	});
}

function addOrEditCouponDialog(action, updateId) {
	var url = website + "boCoupon/insertPage";
	var params = null;
	if(action == ACTION_EDIT){
		var ids = null;
		if(updateId == null){
			ids = getSelectedItems("checkKey");
			if (ids == "" || ids.split(",").length != 1) {
				alert("请只选择一个优惠券");
				return;
			}
		}else{
			ids = updateId;
		}
		params = {
			couponid : ids
		}
		url = website + "boCoupon/updatePage";
	}
	
	$("#curAction").val(action);
	
	mask.open(true);
	ajaxGet(url, params, function(result) { 
		$("#dialog-form-coupon").html(result);
		$("#dialog-form-coupon") .dialog({
			width : 450,
			modal : true,
			resizable : false,
			buttons : {
				"确定" : function() {
					saveCoupon();
				},
				"取消" : function() {
					$(this).dialog("close");
				}
			},
			close : function() {
				allFields.val("").removeClass("ui-state-error");
				$(this).html("");
			}
		});
		mask.close();
	}, "html");
}


function saveCoupon(){
	var smallpicture = $("#smallpicture");
	var largepicture = $("#largepicture");
	var desc = $("#desc");
	var allFields = $([]).add(smallpicture).add(largepicture).add(desc), tips = $(".validateTips");
	
	var bValid = true;
	allFields.removeClass("ui-state-error");
	if($("#curAction").val() == ACTION_ADD){
		bValid = bValid&& checkLength(smallpicture, "小图片",1, 100, tips);
		bValid = bValid&& checkLength(largepicture, "大图片",1, 100, tips);
	}
	if (bValid) {
		$("#couponForm").submit();
	}
}

function search(){
	searchWithPage();
}

function getPage(pageIndex){
	searchWithPage(pageIndex);
}

function searchWithPage(pageIndex){
	var categoryType = $("#categoryType").val();
	var searchText = $("#searchText").val();
	var params = null;
	if(pageIndex != null){
		params = {
			categoryType:categoryType,
			searchText:searchText,
			page:pageIndex
		}
	}else{
		params = {
			categoryType:categoryType,
			searchText:searchText
		}
	}
	mask.open(true);
	ajaxGet(website + "boCoupon/search",params,function(result){
		var tabOrder = $("#currentTabOrder").val();
		$("#tabs-"+tabOrder).html(result);
		initCoupon();
		mask.close();
	},"html");
}